import { Space, Avatar, Typography, Button } from "antd";
import { CommentReplyItem } from "./shareType.ts"; // 导入接口定义
import { useSelector } from "react-redux";
import { RootState } from "@/store/index.ts";
import { useState } from "react";
import { ArticleDetail } from "@/apis/shared.ts";
import { userDeleteReply } from "@/apis/articlesApi.ts";

const { Paragraph } = Typography;

/**
 * 渲染评论的回复
 * @param comment
 * @param level
 */
interface CommentReplyProps {
  reply: CommentReplyItem;
  level: number;
  article: ArticleDetail;
  commentId: string;
  setArticle: (article: ArticleDetail) => void;
}
const CommentReply: React.FC<CommentReplyProps> = ({
  reply,
  level,
  article,
  commentId,
  setArticle,
}) => {
  // 判断是否是评论的回复的作者
  const flag =
    useSelector((state: RootState) => state.UserInfoStore.email) ===
    reply.authorEmail;

  // 判断是否是文章作者
  const [isUserReply] = useState(flag);

  // 删除评论的逻辑
  const handleDeleteReply = async () => {
    // 调用删除评论的接口
    const res = await userDeleteReply(article._id, commentId, reply._id);

    // 如果删除成功，则更新文章的评论列表
    if (res.code === 200) {
      // 获取评论的列表
      const tempCommentList = article.commentList;
      // 找到当前评论的索引
      const tempCommentIndex = tempCommentList.findIndex(
        (item) => item._id === commentId
      );
      // 修改评论的回复列表
      tempCommentList[tempCommentIndex].replyList = tempCommentList[
        tempCommentIndex
      ].replyList.filter((item) => item._id !== reply._id);

      // 更新文章的评论列表
      setArticle({
        ...article,
        commentList: tempCommentList,
      });
    }

    console.log("删除评论的逻辑");
  };

  return (
    <Space direction="vertical" style={{ paddingLeft: level * 20 }}>
      <Space>
        <Avatar src={reply.authorAvatar} shape="square" size={32 + level * 2} />
        <Typography.Text strong>{reply.authorNickName}</Typography.Text>
        <Typography.Text>{reply.createTime}</Typography.Text>
        <Typography.Text>
          {isUserReply && (
            <Button type="link" onClick={handleDeleteReply}>
              删除
            </Button>
          )}
        </Typography.Text>
      </Space>
      <Paragraph>{reply.content}</Paragraph>
    </Space>
  );
};

export default CommentReply;
